package com.dingding.special.user.userinfo.service.impl;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.daox.ICriteriaBaseDao;
import com.dingding.common.core.base.dto.AbstractValiResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.special.Specialuserinfo;
import com.dingding.common.core.beans.special.Specialuserlogin;
import com.dingding.common.core.im.IInstantMessenger;
import com.dingding.common.core.im.InstantMessengerFactory;
import com.dingding.common.core.im.dto.FormatType;
import com.dingding.common.core.upload.ImageUpload;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.paravalidate.ValiResult;
import com.dingding.common.core.util.paravalidate.ValidateUtil;
import com.dingding.special.user.deposit.code.DepositCodeMsg;
import com.dingding.special.user.userinfo.dao.ISpecialUserInfoDao;
import com.dingding.special.user.userinfo.dto.ReqGetTokenByRongCloud;
import com.dingding.special.user.userinfo.dto.ReqGetUserInfoDTO;
import com.dingding.special.user.userinfo.dto.ReqUpdateUserAvatarDTO;
import com.dingding.special.user.userinfo.dto.ReqUpdateUserInfoDTO;
import com.dingding.special.user.userinfo.dto.ReqUserDatumDTO;
import com.dingding.special.user.userinfo.dto.ResGetTokenByRongCloud;
import com.dingding.special.user.userinfo.dto.ResGetUserInfoDTO;
import com.dingding.special.user.userinfo.dto.ResUpdateUserAvatarDTO;
import com.dingding.special.user.userinfo.dto.ResUpdateUserInfoDTO;
import com.dingding.special.user.userinfo.dto.ResUserDatumDTO;
import com.dingding.special.user.userinfo.message.UserInfoCodeMsg;
import com.dingding.special.user.userinfo.service.ISpecialUserInfoService;

/**
 * 
 * @ClassName: SpecialUserInfoServiceImpl 
 * @Description: 获取用户信息(融云使用)
 * @author YHQ
 * @date 2016年8月23日 下午5:12:11
 * @since V2.4.0
 * 
 */
@Component("specialUserInfoService")
public class SpecialUserInfoServiceImpl extends AbstractValiResponse implements ISpecialUserInfoService {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource(name = "specialUserInfoDao")
	private ISpecialUserInfoDao specialUserInfoDao;

	@Resource(name = "criteriaBaseDao")
	private ICriteriaBaseDao criteriaBaseDao;

	// 获取IM通信对象
	private IInstantMessenger instantMessenger = InstantMessengerFactory.createInstantMessengerPaltform();

	/**
	 * 
	 * @Title: getUserInfos 
	 * @Description: 获取IM聊天需要的用户信息
	 * @param  reqGetUserInfoDTO 
	 * @author YHQ 
	 * @since V2.4.0
	 * @return ResponseEntity<ResGetUserInfoDTO>    返回类型
	 * 
	 */
	@Override
	public ResponseEntity<ResGetUserInfoDTO> getRongCloudInfo(ReqGetUserInfoDTO reqGetUserInfoDTO) {

		// 获取用户信息响应Bean
		ResponseEntity<ResGetUserInfoDTO> response = new ResponseEntity<ResGetUserInfoDTO>();

		// 验证客户端请求参数是否为空
		boolean flag = this.validateParam(response, reqGetUserInfoDTO);

		if (!flag) {
			return response;
		}

		// 获取用户信息
		ResGetUserInfoDTO resGetUserInfoDTO = specialUserInfoDao.getUserInfo(reqGetUserInfoDTO.getUserId());

		// 判断用户信息是否为空
		if (resGetUserInfoDTO == null) {

			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);
			response.setPromptMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);
			return response;
		}

		resGetUserInfoDTO.setUserTabloidAvatar(ToolUtil.imageAddress(resGetUserInfoDTO.getUserTabloidAvatar()));
		
		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resGetUserInfoDTO);

		return response;
	}

	/**
	 * 
	 * @Title: validateParam 
	 * @Description: 验证客户端请求参数是否为空 
	 * @param reqGetUserInfoDTO 获取用户信息 客户端请求参数
	 * @author YHQ 
	 * @since V2.4.0
	 * @return boolean    返回类型
	 * 
	 */
	public boolean validateParam(ResponseEntity<ResGetUserInfoDTO> response, ReqGetUserInfoDTO reqGetUserInfoDTO) {

		// 判断客户端请求数据是否为空
		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqGetUserInfoDTO, ReqGetUserInfoDTO.class);

		if (!valiResult.isAvailable()) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(DepositCodeMsg.DATA_NULL_PARAM_MESSAGE);// 客户端请求数据为空
			response.setPromptMessage(DepositCodeMsg.APP_ERROR);// 客户端请求数据为空
			response.setNullProperties(valiResult.getNullFieldName());
			log.error("为空字段为：" + valiResult.getNullFieldName());
			return false;
		}

		return true;
	}

	/**
	 * 
	 * @Title: updateUserInfo 
	 * @Description: 修改用户信息 
	 * @param reqUpdateUserInfoDTO 修改用户信息请求Bean
	 * @author YHQ 
	 * @since V2.4.0 
	 * @return ResponseEntity<ResUpdateUserInfoDTO>    返回类型
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseEntity<ResUpdateUserInfoDTO> updateUserInfo(ReqUpdateUserInfoDTO reqUpdateUserInfoDTO) {

		// 修改用户信息响应Bean
		ResponseEntity<ResUpdateUserInfoDTO> response = new ResponseEntity<ResUpdateUserInfoDTO>();

		// 验证修改用户信息请求参数是否为空
		boolean flag = this.validateUserInfo(response, reqUpdateUserInfoDTO);

		if (!flag) {
			return response;
		}

		// 修改用户信息操作
		this.updateUserInfoOperation(response, reqUpdateUserInfoDTO);

		return response;
	}

	/**
	 * 
	 * @Title: validateUserInfo 
	 * @Description: 验证修改用户信息请求参数 
	 * @param @return    设定文件 
	 * @author YHQ 
	 * @return boolean    返回类型
	 * 
	 */
	public boolean validateUserInfo(ResponseEntity<ResUpdateUserInfoDTO> response,
			ReqUpdateUserInfoDTO reqUpdateUserInfoDTO) {

		// 判断客户端请求数据是否为空
		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqUpdateUserInfoDTO, ReqUpdateUserInfoDTO.class);

		if (!valiResult.isAvailable()) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(DepositCodeMsg.DATA_NULL_PARAM_MESSAGE);// 客户端请求数据为空
			response.setPromptMessage(DepositCodeMsg.APP_ERROR);// 客户端请求数据为空
			response.setNullProperties(valiResult.getNullFieldName());
			log.error("为空字段为：" + valiResult.getNullFieldName());
			return false;
		}

		return true;
	}

	/**
	 * 
	 * @Title: updateUserInfoOperation 
	 * @Description: 修改用户信息操作
	 * @param response 修改用户信息响应Bean
	 * @param reqUpdateUserInfoDTO  修改用户信息客户端请求参数
	 * @author YHQ 
	 * @return void    返回类型
	 * 
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateUserInfoOperation(ResponseEntity<ResUpdateUserInfoDTO> response,
			ReqUpdateUserInfoDTO reqUpdateUserInfoDTO) {

		// 修改用户信息响应Bean
		ResUpdateUserInfoDTO resUpdateUserInfoDTO = new ResUpdateUserInfoDTO();

		// 根据用户Id获取用户信息
		Specialuserinfo specialuserinfo = specialUserInfoDao.getSpecialUserInfo(reqUpdateUserInfoDTO.getUserId());

		// 判断用户是否存在
		if (specialuserinfo == null) {

			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);// 用户不存在
			response.setPromptMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);// 用户不存在
			return;
		}

		// 年龄
		if (reqUpdateUserInfoDTO.getAge() != null) {
			specialuserinfo.setAge(reqUpdateUserInfoDTO.getAge());
		}

		// 昵称
		if (ToolUtil.isNotBlank(reqUpdateUserInfoDTO.getNickName())) {
			specialuserinfo.setNickName(reqUpdateUserInfoDTO.getNickName());
		}

		// 职业
		if (ToolUtil.isNotBlank(reqUpdateUserInfoDTO.getOccupation())) {
			specialuserinfo.setOccupation(reqUpdateUserInfoDTO.getOccupation());
		}

		// 籍贯
		if (ToolUtil.isNotBlank(reqUpdateUserInfoDTO.getOrigin())) {
			specialuserinfo.setOrigin(reqUpdateUserInfoDTO.getOrigin());
		}

		// 性别
		if (reqUpdateUserInfoDTO.getSex() != null) {
			specialuserinfo.setSex(reqUpdateUserInfoDTO.getSex());
		}

		// 用户Id
		if (ToolUtil.isNotBlank(reqUpdateUserInfoDTO.getUserId())) {
			specialuserinfo.setUserId(reqUpdateUserInfoDTO.getUserId());
		}

		// 用户信息
		resUpdateUserInfoDTO.setUserId(specialuserinfo.getUserId());

		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resUpdateUserInfoDTO);

	}

	/**
	 * 
	 * @Title: getTokenByRongCloud 
	 * @Description: 获取Token
	 * @param reqGetTokenByRongCloud 获取Token客户端请求Bean
	 * @author YHQ 
	 * @since V2.4.0
	 * @return ResponseEntity<ResGetTokenByRongCloud>    返回类型
	 * 
	 */
	@Override
	public ResponseEntity<ResGetTokenByRongCloud> getTokenByRongCloud(ReqGetTokenByRongCloud reqGetTokenByRongCloud) {

		// 获取token响应Bean
		ResponseEntity<ResGetTokenByRongCloud> response = new ResponseEntity<ResGetTokenByRongCloud>();

		ResGetTokenByRongCloud resGetTokenByRongCloud = new ResGetTokenByRongCloud();

		// 验证客户端请求参数是否空
		boolean flag = this.validateRongCloudToken(response, reqGetTokenByRongCloud);

		if (!flag) {
			return response;
		}

		// 获取用户登录信息
		Specialuserlogin specialuserlogin = specialUserInfoDao.getSpecialUserLogin(reqGetTokenByRongCloud.getUserId());

		// 获取用户详情
		Specialuserinfo specialuserinfo = specialUserInfoDao.getSpecialUserInfo(reqGetTokenByRongCloud.getUserId());

		if (specialuserlogin == null) {

			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);// 用户不存在
			response.setPromptMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);// 用户不存在
			return response;
		}
		
		// 获取token
		String token = instantMessenger.getToken(specialuserinfo.getUserId(), specialuserinfo.getNickName(),
				ToolUtil.imageAddress(specialuserinfo.getUserTabloidAvatar()), FormatType.json);
		
		specialuserlogin.setRongCloudToken(token);

		resGetTokenByRongCloud.setToken(specialuserlogin.getRongCloudToken());

		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resGetTokenByRongCloud);

		return response;
	}

	/**
	 * 
	 * @Title: validateRongCloudToken 
	 * @Description: 验证获取融云token客户端请求参数
	 * @param @param response
	 * @param @param reqGetTokenByRongCloud    设定文件 
	 * @author YHQ 
	 * @since V2.4.0 
	 * @return void    返回类型
	 * 
	 */
	public boolean validateRongCloudToken(ResponseEntity<ResGetTokenByRongCloud> response,
			ReqGetTokenByRongCloud reqGetTokenByRongCloud) {

		// 判断客户端请求数据是否为空
		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqGetTokenByRongCloud,
				ReqGetTokenByRongCloud.class);

		if (!valiResult.isAvailable()) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(DepositCodeMsg.DATA_NULL_PARAM_MESSAGE);// 客户端请求数据为空
			response.setPromptMessage(DepositCodeMsg.APP_ERROR);// 客户端请求数据为空
			response.setNullProperties(valiResult.getNullFieldName());
			log.error("为空字段为：" + valiResult.getNullFieldName());
			return false;
		}

		return true;

	}

	/**
	 * 
	 * @Title: getUserDatum 
	 * @Description: 获取用户资料
	 * @param reqUserDatumDTO 获取用户资料客户端请求Bean
	 * @author YHQ 
	 * @since V2.4.0
	 * @return ResponseEntity<ResUserDatumDTO>    返回类型
	 * 
	 */
	@Override
	public ResponseEntity<ResUserDatumDTO> getUserDatum(ReqUserDatumDTO reqUserDatumDTO) {

		ResponseEntity<ResUserDatumDTO> response = new ResponseEntity<ResUserDatumDTO>();

		// 验证客户端请求参数是否为空
		boolean flag = this.validateDatum(response, reqUserDatumDTO);

		if (!flag) {
			return response;
		}

		// 获取用户资料
		ResUserDatumDTO resUserDatumDTO = specialUserInfoDao.getUserDatum(reqUserDatumDTO.getUserId());
		
		//判断年龄等于0，不为空则至为null
		if(resUserDatumDTO.getAge() == 0){
			resUserDatumDTO.setAge(null);
		}
		
		//判断籍贯是n，不为空则至为null
		if("N".equals(resUserDatumDTO.getOccupation())){
			resUserDatumDTO.setOccupation(null);
		}
		
		//判断职业是n，不为空则至为null
		if("N".equals(resUserDatumDTO.getOrigin())){
			resUserDatumDTO.setOrigin(null);
		}
		
		// 判断该用户是否存在
		if (resUserDatumDTO == null) {

			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);// 用户不存在
			response.setPromptMessage(UserInfoCodeMsg.USER_IS_NOT_EXIST);// 用户不存在
			return response;
		}

		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resUserDatumDTO);

		return response;
	}

	/**
	 * 
	 * @Title: validateRongCloudToken 
	 * @Description: 验证获取融云token客户端请求参数
	 * @param @param response
	 * @param @param reqGetTokenByRongCloud    设定文件 
	 * @author YHQ 
	 * @since V2.4.0 
	 * @return void    返回类型
	 * 
	 */
	public boolean validateDatum(ResponseEntity<ResUserDatumDTO> response, ReqUserDatumDTO reqUserDatumDTO) {

		// 判断客户端请求数据是否为空
		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqUserDatumDTO, ReqUserDatumDTO.class);

		if (!valiResult.isAvailable()) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(DepositCodeMsg.DATA_NULL_PARAM_MESSAGE);// 客户端请求数据为空
			response.setPromptMessage(DepositCodeMsg.APP_ERROR);// 客户端请求数据为空
			response.setNullProperties(valiResult.getNullFieldName());
			log.error("为空字段为：" + valiResult.getNullFieldName());
			return false;
		}

		return true;

	}

	/**
	 * 
	 * 修改用户头像
	 * 
	 * @Title: updateUserAvatar 
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public ResponseEntity<ResUpdateUserAvatarDTO> updateUserAvatar(ReqUpdateUserAvatarDTO reqUpdateUserAvatarDTO) {
		// 判断客户端请求数据是否为空
		ValiResult valiResult = ValidateUtil.validateBeanIsAvaliable(reqUpdateUserAvatarDTO,
				ReqUpdateUserAvatarDTO.class);

		if (!valiResult.isAvailable()) {
			return super.error(valiResult);
		}

		Criterion criterion = Restrictions.eq("userId", reqUpdateUserAvatarDTO.getUserId());
		Specialuserinfo specialuserinfo = criteriaBaseDao.queryCriteriaListUnique(Specialuserinfo.class, criterion);

		// 用户不存在
		if (specialuserinfo == null) {
			return super.error(HttpStatus.SC_FORBIDDEN, UserInfoCodeMsg.APP_ERROR, UserInfoCodeMsg.USER_IS_NOT_EXIST);
		}

		// 生成图片名称
		String userAvatarName = ToolUtil.creatImageName();
		// 压缩的图片名称
		String userCompressAvatarName = ToolUtil.creatImageName();

		// 执行图片上传
		ImageUpload imageUpload = new ImageUpload();
		boolean isSuccess = imageUpload.userAvatarUpload(reqUpdateUserAvatarDTO.getUserAvatar(), userAvatarName,
				userCompressAvatarName, specialuserinfo.getUserAvatar(), specialuserinfo.getUserTabloidAvatar());

		if (!isSuccess) { // 上传失败
			return super.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, UserInfoCodeMsg.IMAGE_UPLOAD_ERROR, UserInfoCodeMsg.SERVER_ERROR);
		}

		// 头像名称
		specialuserinfo.setUserAvatar(userAvatarName);
		// 头像缩略图地址
		specialuserinfo.setUserTabloidAvatar(userCompressAvatarName);

		ResUpdateUserAvatarDTO resUpdateUserAvatarDTO = new ResUpdateUserAvatarDTO();
		resUpdateUserAvatarDTO.setUserAvatar(userAvatarName); // 更改后的用户头像地址
		resUpdateUserAvatarDTO.setUserTabloidAvatar(userCompressAvatarName); // 更改后的用户缩略头像地址

		return super.success(resUpdateUserAvatarDTO, HttpStatus.SC_OK);

	}

}
